#!/bin/sh
#---------------------------------------------------------------------------------
# backuphdr.sh
# 
# This shell script is invoked to perform a backup of the HMC hard drive for Disaster
# Recovery purposes. All of the files that have changed since the code was installed
# on the hard disk will be placed into a compressed tar file.
#
# Based on the arguements passed into this program, the output file will either
# be written to DVD media, copied to a mounted remote server resource, or ftp'd
# to a remote FTP server.
#
# 
# Usage: backuphdr <archive name>  (in the format: HMCBackup_yyyyMMdd.HHmmss.tgz)
#                  <backup type>   (0=DVD, 1=remote mount, 2=ftp)
#
#                  if type 1...
#                  <server>        (remote server name)
#                  <resource>      (remote server resource)
#                  <fstype>        (file system type)
#                  <options>       (other 'mount' command options)
#
#                  if type 2...
#                  <server>        (remote ftp server)
#                  <userID>        (userID for ftp access)
#                  <password>      (password for ftp access)
#
# Return Codes:
# 1 - Error locating required backup directory
# 2 - unable to start portmap
# 3 - Error unmounting the media
# 4 - Media is write-protected
# 5 - Error mounting the media
# 6 - Other errors ('tar' command error)


# common exit point for script
exit_cleanup() {
    rm -f $MOUNT_OUTPUT
    
    # this temp working file may or may not exist. Ensure it is removed prior to exiting
    rm -f /var/hsc/log/ftp.log
    
    if [ $1 -eq 0 ]; then
	echo "Backup of critical system data completed successfully on `date`." >> $LOG
    else
	echo "Backup of critical system data exited (with errors) on `date`." >> $LOG
    fi
    exit $1
}  


#---------------------------------------------------------------------------------
# test if DVD is able to be mounted
#---------------------------------------------------------------------------------
function checkDVD_Access {

    DIR=$1
    FILE=$2
    MTPT=$3
    funcRC=0

    # Check to see if media is already mounted - if so then unmount it
    if grep "$MTPT" /etc/mtab; then # Media is already mounted
        if ! umount $MTPT >> $LOG 2>&1; then
            echo "Couldn't unmount the media, $MTPT." >> $LOG
            funcRC=3
        fi
    fi

    # Mount the media and check for write-protect
    mount -v $MTPT > $MOUNT_OUTPUT 2>&1
    if [ $? -eq 0 ]; then
        echo "Mounted the media." >> $LOG
        if grep "write-protected" $MOUNT_OUTPUT; then
            echo "The media is write-protected." >> $LOG
            umount $MTPT
            funcRC=4
        else
            # attempt to copy some test data
            cp $DIR/$FILE $MTPT
            if [ $? -eq 0 ]; then
                # destination is OK. Remove the test file
                rm -f $MTPT/$FILE
                umount $MTPT
                funcRC=0
            else
                funcRC=7
            fi
        fi
    else
        echo "Couldn't mount the media, $MTPT." >> $LOG
        funcRC=5
    fi    
    
    echo "Exiting checkDVD_Access, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# test if mountpoint reachable
#---------------------------------------------------------------------------------
function checkMount_Access {

    DIR=$1
    FILE=$2
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    funcRC=0
    
    # make test mount point
    cd /mnt
    mkdir remote
    cd -
    MTPT=/mnt/remote
    
    # attempt to mount
    # NFS example:
    #   mount -o vers=2 -o proto=udp <server>:<resource> <mount point>
    # Samba example:
    #   mount -t smbfs -o username=xxx,password=yyy //<server>/<resource> <mount point>
    mount $OPTIONS $SERVER:$RESOURCE $MTPT
    if [ $? -eq 0 ]; then
        cp $DIR/$FILE $MTPT
        if [ $? -eq 0 ]; then
            # destination is OK
            rm -f $MTPT/$FILE
            umount $MTPT
            funcRC=0
        else
            funcRC=11
        fi
    else
        # unable to mount
        funcRC=10
    fi
        
    echo "Exiting checkMount_Access, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# test if ftp server reachable
#---------------------------------------------------------------------------------
function checkFTP_Access {

    DIR=$1
    FILE=$2
    SERVER=$3
#   CUR_DIR=$4
    USER=$4
    PASSWORD=$5
    
    # change dir to $DIR
    cd $DIR
    
    /usr/kerberos/bin/ftp -n -u -v $SERVER <<EOF 2>&1 > /var/hsc/log/ftp.log
user $USER $PASSWORD
bin
put $FILE
quit
EOF

    # 
    # First, test if the file transfer succeeded, then if not, check for
    # any specific errors (login, etc)
    #
    
    # Look for "Transfer complete", "Successful transfer" or equivalent msg
    # code. Careful on grep'ing for this value - note the space
    grep -i "^226 " /var/hsc/log/ftp.log 2>&1 >/dev/null
    if [ $? -eq 0 ]; then
        # successful file transfer!
        rm -f /var/hsc/log/ftp.log
        funcRC=0
    else
        # If no file transfer, look for (known) errors
        grep -i "not logged in" /var/hsc/log/ftp.log > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            # Oops - error logging in
            funcRC=21
        else
            grep -i "Connection refused" /var/hsc/log/ftp.log > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                # Oops - error accessing server
                funcRC=23
            else
                grep -i "unknown host" /var/hsc/log/ftp.log > /dev/null 2>&1
                if [ $? -eq 0 ]; then
                    # Oops - error accessing server
                    funcRC=24
                else
                    grep -i "Not connected" /var/hsc/log/ftp.log > /dev/null 2>&1
                    if [ $? -eq 0 ]; then
                        # Oops - error accessing server
                        funcRC=25
                    else
                        # one more login check...
                        grep -i "Login failed" /var/hsc/log/ftp.log > /dev/null 2>&1
                        if [ $? -eq 0 ]; then
                            # Oops - error logging in
                            funcRC=22
                        else
                            # assuming past these login checks, now check for successful file xfer
                            grep -i "Permission denied" /var/hsc/log/ftp.log > /dev/null 2>&1
                            if [ $? -eq 0 ]; then
                                # permission issues
                                funcRC=26
                            else
                                # All other errors here
                                funcRC=27
                            fi
                        fi 
                    fi 
                fi
            fi
        fi   
    fi
                            
    # switch back to original directory
    cd -
   
    echo "Exiting checkFTP_Access, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# offload dump to DVD
#---------------------------------------------------------------------------------
function copyDumpToDVD {

    DIR=$1
    FILE=$2
    MTPT=$3
    funcRC=0

        
    # copy the dump
    mount $MTPT
    if [ $? -eq 0 ]; then
        #
        # Special case for local media: copy to DVD media as hardcoded filename 'backuphdr.tgz'
        #
        cp $DIR/$FILE $MTPT/backuphdr.tgz
        if [ $? -eq 0 ]; then
            funcRC=0
        else
            funcRC=7
        fi
    else    
        # unable to mount
        funcRC=5
    fi
    
    # remove the working archive file
    rm -f $DIR/$FILE
    
    umount $MTPT
    echo "Exiting copyDumpToDVD, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# offload dump to mounted server
#---------------------------------------------------------------------------------
function copyDumpToMount {

    DIR=$1
    FILE=$2
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    funcRC=0
    
    # set local mount point - this directory on the HMC should be established by now
    MTPT=/mnt/remote
    
    # attempt to mount
    # NFS example:
    #   mount -o vers=2 -o proto=udp <server>:<resource> <mount point>
    # Samba example:
    #   mount -t smbfs -o username=xxx,password=yyy //<server>/<resource> <mount point>
    mount $OPTIONS $SERVER:$RESOURCE $MTPT
    if [ $? -eq 0 ]; then
        cp $DIR/$FILE $MTPT
        if [ $? -eq 0 ]; then
            funcRC=0
        else
            funcRC=11
        fi
    else
        # unable to mount
        funcRC=10
    fi
    
    # remove the working archive file
    rm -f $DIR/$FILE
        
    umount $MTPT
    echo "Exiting copyDumpToMount, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



#---------------------------------------------------------------------------------
# offload dump to ftp
#---------------------------------------------------------------------------------
function ftpDumpToServer {

    DIR=$1
    FILE=$2
    SERVER=$3
#   CUR_DIR=$4
    USER=$4
    PASSWORD=$5
    
    # change dir to $DIR
    cd $DIR
    
        /usr/kerberos/bin/ftp -n -u -v $SERVER <<EOF 2>&1 > /var/hsc/log/ftp.log
user $USER $PASSWORD
bin
put $FILE
quit
EOF

    # 
    # First, test if the file transfer succeeded, then if not, check for
    # any specific errors (login, etc)
    #
    
    # Look for "Transfer complete", "Successful transfer" or equivalent msg
    # code. Careful on grep'ing for this value - note the space
    grep -i "^226 " /var/hsc/log/ftp.log 2>&1 >/dev/null
    if [ $? -eq 0 ]; then
        # successful file transfer!
        funcRC=0
    else
        # If no file transfer, look for (known) errors
        grep -i "not logged in" /var/hsc/log/ftp.log > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            # Oops - error logging in
            funcRC=21
        else
            grep -i "Connection refused" /var/hsc/log/ftp.log > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                # Oops - error accessing server
                funcRC=23
            else
                grep -i "unknown host" /var/hsc/log/ftp.log > /dev/null 2>&1
                if [ $? -eq 0 ]; then
                    # Oops - error accessing server
                    funcRC=24
                else
                    grep -i "Not connected" /var/hsc/log/ftp.log > /dev/null 2>&1
                    if [ $? -eq 0 ]; then
                        # Oops - error accessing server
                        funcRC=25
                    else
                        # one more login check...
                        grep -i "Login failed" /var/hsc/log/ftp.log > /dev/null 2>&1
                        if [ $? -eq 0 ]; then
                            # Oops - error logging in
                            funcRC=22
                        else
                            # assuming past these login checks, now check for successful file xfer
                            grep -i "Permission denied" /var/hsc/log/ftp.log > /dev/null 2>&1
                            if [ $? -eq 0 ]; then
                                # permission issues
                                funcRC=26
                            else
                                # All other errors here
                                funcRC=27
                            fi
                        fi 
                    fi 
                fi
            fi
        fi   
    fi
   
    # remove the working archive file
    rm -f $DIR/$FILE
    
    # switch back to original directory
    cd -
   
    echo "Exiting ftpDumpToServer, funcRC = $funcRC." >> $LOG
    return $funcRC
}  



# --------------  End Subroutines --------------------------------------------



# --------------- BEGIN MAIN PROGRAM  ----------------------------------------

#---------------------------------------------------------------------------------
# directory and filename which records the backup actions.
#---------------------------------------------------------------------------------
LOGDIR=/var/hsc/log
LOG=$LOGDIR/backuphdr.log
   
LOG_ERROR_LOG=/tmp/backuphdr.log
MOUNT_OUTPUT=/tmp/mountInfo

CTBACKUP=/usr/sbin/rsct/bin/ctbackup

#
# Just in case we have NLS troubles reading system information...
#
LANG=en_US
export LANG

#---------------------------------------------------------------------------------
# mount point: the mount point for the media to which the backup is to be stored
# ??? - this must be changed to mount point for DVD RAM
# mountpoint for DVD-RAM now defined (yes, it really is to /media/cdrom. 'fstab'
# entry wil automount correct physical device) 4/25/01 - SLF
#---------------------------------------------------------------------------------
DVD_MOUNTPOINT=/media/cdrom

#---------------------------------------------------------------------------------
# the filename and backup type of the HMC archive
#---------------------------------------------------------------------------------
ARCHIVE=$1
BACKUP_TYPE=$2

# generate some test data
DUMP_DIR=/dump
TEST_ACCESS_FILE=$ARCHIVE
echo "test access" > $DUMP_DIR/$TEST_ACCESS_FILE

#---------------------------------------------------------------------------------
# a file whose date and time reflect when the build of the HMC was *installed* and
# a file which indicates the last RPM package installation date (see modHscBuildDat)
#---------------------------------------------------------------------------------
MARKER=/opt/hsc/com/ibm/hsc/websm/launch/hscmgt/hscbuild.dat
MARKER2=/opt/hsc/com/ibm/hsc/websm/launch/hscmgt/rpminst.dat


# Check if the directory for the log file exists.
if [ ! -d $LOGDIR ]; then
    echo "=================================================================" > $LOG_ERROR_LOG
    echo -e "Backup task log for `date`." >> $LOG_ERROR_LOG
    echo "Backup task log directory, <$LOGDIR>, does not exist. Program exiting" >> $LOG_ERROR_LOG
    exit_cleanup 1
fi

# Start log to record backup actions.
echo -e "Backup log for `date`, archive name is $ARCHIVE.\n" > $LOG


#
# Before doing any backup operations, test first if we can access the output
# device/resource/site
#
if [ $BACKUP_TYPE -eq 0 ]; then

    # output to DVD
    echo "input args are: <$1> <$2>" >> $LOG
    echo "testing DVD access..." >> $LOG
    checkDVD_Access $DUMP_DIR $TEST_ACCESS_FILE $DVD_MOUNTPOINT
    checkRC=$?
    if [ $checkRC -ne 0 ]; then
        rm -f $DUMP_DIR/$TEST_ACCESS_FILE
        exit_cleanup $checkRC
    fi
   
elif [ $BACKUP_TYPE -eq 1 ]; then

    # to remote (NFS/Samba) mount. Grab remaining program args from input
    echo "input args are: <$1> <$2> <$3> <$4> <$5> <$6>" >> $LOG
    echo "testing mount access..." >> $LOG
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    
    # First determine if portmap is running - it should not be.
    # Then start that service for the duration of this script
    PORTMAP=/sbin/portmap
    PORTMAP_SHORT=portmap
    PID=`ps -ef | grep $PORTMAP_SHORT | grep -v grep | awk '{print $2}'`
    
    if test -n "$PID" ; then
        echo "portmap is currently executing, PID is $PID." >> $LOG
    else
        # echo No PID, so start the service.
	echo "about to start the portmap service..." >> $LOG
        /etc/init.d/portmap start
        RC=$?
        sleep 1
     
        # save away this PID for later process termination    
        NEW_PID=`ps -ef | grep $PORTMAP_SHORT | grep -v grep | awk '{print $2}'`
        
        if test -n "$NEW_PID" ; then
            echo "portmap started successfully, pid is $NEW_PID" >> $LOG
        else
            echo "unable to start the portmap daemon, rc = $RC" >> $LOG
            exit_cleanup 2
        fi
    fi

    checkMount_Access $DUMP_DIR $TEST_ACCESS_FILE $SERVER $RESOURCE $FSTYPE "$OPTIONS"
    checkRC=$?
    if [ $checkRC -ne 0 ]; then
        echo "error attempting mount access, killing portmap..." >> $LOG
        
        if test -n "$PID" ; then
            echo "was running prior to script execution - not terminating the service.">> $LOG
        else
            echo "about to terminate the portmap daemon...">> $LOG
            kill -9 $NEW_PID
        fi
        rm -f $DUMP_DIR/$TEST_ACCESS_FILE
        exit_cleanup $checkRC
    fi
   
elif [ $BACKUP_TYPE -eq 2 ]; then

    # to ftp server. Grab remaining program args from input
    echo "input args are: <$1> <$2> <$3> <$4> <password>" >> $LOG
    echo "testing ftp access..." >> $LOG
    SERVER=$3
    USERID=$4
    PASSWORD=$5
    checkFTP_Access $DUMP_DIR $TEST_ACCESS_FILE $SERVER $USERID $PASSWORD
    checkRC=$?
    if [ $checkRC -ne 0 ]; then
        rm -f $DUMP_DIR/$TEST_ACCESS_FILE
        exit_cleanup $checkRC
    fi
    
else
    # exit, error - invalid input parameter
    rm -f $DUMP_DIR/$TEST_ACCESS_FILE
    exit_cleanup 8
fi

# All done with the test file, now remove it
rm -f $DUMP_DIR/$TEST_ACCESS_FILE


#
# Generate a list of *most* (not *all*) of the files that have changed since the
# code was installed on the hard disk (as indicated by the marker file).
#
# Set the file to output this list of files to. This avoids the problem of overflowing
# the 'tar' input buffer if too many files are present.
#
# Make sure to catch the sybolic link'd files too and also set up the filter
# to catch ".*" files as well
#
# Currently, there are still issues with saving directories only.  Problem is
# if we identify a directory to backup, the 'tar' command seems to decend into
# that directory and save all files contained in that directory whether or not
# they meet the date filtering criteria. See the comments in the 'restore' script
# for further details regarding users' home directories.
#
# Some files still get archived that shouldn't (some PID files, for example),
# but the system seems tolerant of the recovery of these files.
#
echo -e "list of files to archive now follows...\n" >> $LOG
mount /mnt/dos

FILELIST=/tmp/backup.list
`find / -name '*' -xtype f ! -path '/var/lock/subsys/*' ! -path '/opt/hsc/com/ibm/hsc/websm/launch/hscmgt/rpminst.dat' ! -path '/extra-swap' ! -path '/var/hsc/log/backuphdr.log' ! -path '/tmp/archive.log' ! -path '/tmp/backup.list' ! -path '/proc/*' ! -path '/dump/*' ! -path '/info/*' ! -path '/updates/*' ! -path '/var/ct/*' ! -path '/extra/updates/*' ! -type b ! -type c ! -type p ! -type s -newer $MARKER -print > $FILELIST`
`find / -name '.*' -xtype f ! -path '/.journal' ! -path '/var/lock/subsys/*' ! -path '/proc/*' ! -path '/info/*' ! -path '/updates/*' ! -path 'var/ct/*' ! -path '/extra/updates/*' ! -type b ! -type c ! -type p ! -type s -newer $MARKER -print >> $FILELIST`

#
# New for Squadrons (multi-CD installations). Archive the hscbuild.dat file as well
#
echo $MARKER >> $FILELIST

#                      
# Now we need to query all the existing RPM packages on the system in case PTF
# updates added any new RPMs that contain files older than the marker file
#

rpm -qa > /tmp/rpm.list
chmod 777 /tmp/rpm.list

#
# If there is a latest RPM installation date file, use this for RPM comparisons,
# (see modHscBuildDat script). Else, use the file comparison marker file.
#
if [ -f $MARKER2 ]; then
   RPMINSTDATE=$MARKER2
   echo "using latest dated RPM installation package file for RPM date comparisons." >> $LOG
else
   RPMINSTDATE=$MARKER
   echo "using system installation date file for RPM date comparisons." >> $LOG
fi

for i in `cat /tmp/rpm.list`
do
   x=`rpm -qi $i | grep "Install date:" | awk '{print $4" "$5" "$6" "$7" "$8" "$9}'`
   
   # touch temp working file for comparison against marker file using
   # datestamp of installed RPM package
   touch /tmp/rpminst.dat --date="$x"
   chmod 777 /tmp/rpminst.dat

   if [ /tmp/rpminst.dat -nt $RPMINSTDATE ]; then
      # we're newer, so list every file in the package and *selectively* add to save list
      echo "RPM package, $i, installation date is newer than recovery marker file." >> $LOG

      #
      # Send output to a working file first. Then, ensure we're only processing *files*
      # (i.e. not direcories!) next.  Finally, only add the file if it does not already
      # reside in the master list.
      #
      rpm -ql $i > /tmp/rpm.package
      chmod 777 /tmp/rpm.package
      
      for j in `cat /tmp/rpm.package`
      do
         if [ -f $j ]; then
            # only process files, not directory entries
            grep -q $j $FILELIST
            
            if [ $? -ne 0 ]; then
               # we did not find this file, add to master list
               echo $j >> $FILELIST
            fi
         fi
      done
   fi
   
   # stay clean...
   rm -f /tmp/rpminst.dat
done

# bit-o-cleanup
rm -f /tmp/rpm.package
rm -f /tmp/rpm.list

echo "RPM file list generation pre-processing complete" >> $LOG


#
# New feature - 06/09/03.  Incorporate any save upgrade data files
# that may have datestamp prior to the hscbuild.dat ($MARKER) file
#        
# Concatenate the save upgrade file list to the end of the
# dynamically generated backup list.  This save upgrade file
# list gets generated each time after a restore of upgrade
# data is done, hence it'll also be backup'd up too.
#
if [ -f /opt/hsc/data/backupUpgradeList ]; then
   # ensure no file repeats here
   for i in `cat /opt/hsc/data/backupUpgradeList`
   do
      if [ -f $i ]; then
         # only process files, not directory entries
         grep -q $i $FILELIST
            
         if [ $? -ne 0 ]; then
            # we did not find this file, add to master list
            echo $i >> $FILELIST
         fi
      fi
   done
fi


#
# Another new feature - look for the existance of a "special file" containg
# a list of files (currently to be generated by the efix install script)
# and add all these files to the master backup list of files to archive.
#
# We do this in case a package/file has been updated from one release/version
# to another, but the file(s) are still older than the hscbuild.dat file
# AND they are not installed via an RPM install (which the RPM "Install date:"
# would have caught and triggered these files to be backed up). 10/01/03 - SLF
#
if [ -f /opt/hsc/data/extbackupfile.list ]; then
   # ensure no file repeats here
   for i in `cat /opt/hsc/data/extbackupfile.list`
   do
      if [ -f $i ]; then
         # only process files, not directory entries
         grep -q $i $FILELIST
            
         if [ $? -ne 0 ]; then
            # we did not find this file, add to master list
            echo $i >> $FILELIST
         fi
      else
	   if [ -L $i ]; then
              grep -q $i $FILELIST
            
              if [ $? -ne 0 ]; then
               # we did not find this file, add to master list
               echo $i >> $FILELIST
	     fi
	   fi
      fi
   done
fi

 
#
# New RMC requirment (for Megamouth) - ensure *all* files, symlinks, sockets,
# directories in base /var/ct directory get archived.  Ensure the physical
# directory is saved in list prior to symlink entry
#
###for i in `find /var/ct/ -type f -o -type d -o -type s -maxdepth 1`; do
###    if ! grep -q $i $FILELIST; then
###        # we did not find this file, add to master list
###        echo "RMC special processing - added file: $i" >> $LOG
###        echo $i >> $FILELIST
###    fi
###done
#### now do symlinks
###for i in `find /var/ct/ -type l -maxdepth 1`; do
###    if ! grep -q $i $FILELIST; then
###        # we did not find this file, add to master list
###        echo "RMC special processing - added file: $i" >> $LOG
###        echo $i >> $FILELIST
###    fi
###    
###    # special processing for RMC symlink dirs - just save every file under these
###    echo "RMC symlink file detected" >> $LOG
###    for j in `find $i -follow`; do
###        if ! grep -q $j $FILELIST; then
###            echo $j >> $FILELIST
###        fi
###    done
###done
#### always add these RMC files - just in case of timestamping issues
###if ! grep -q "/etc/ct_node_id" $FILELIST; then
###    echo "/etc/ct_node_id" >> $FILELIST
###fi
###if ! grep -q "/var/ct/cfg/ct_node_id" $FILELIST; then
###    echo "/var/ct/cfg/ct_node_id" >> $FILELIST
###fi

#
# Use new RMC backup procedure which generates a unique directory containing
# all their data
#
if [ -f $CTBACKUP ]; then
    # run the RMC backup script
    $CTBACKUP
    
    # above script always returns 0 on exit, so hope for the best...
    if [ -d /var/ct.backup ]; then
        `find /var/ct.backup -name '*' -xtype f ! -type b ! -type c ! -type p ! -type s -print >> $FILELIST`
    fi
fi


 
# Form the name of the archive file by concatenating the directory and filename.
# All backups will go to the /dump partition first
archive="/dump/$ARCHIVE"

#
# Begin the archive process.
# ToDo: Need to check for diskspace problems or other errors before/after tar cmd runs
# Also attempt to verify the archive, but there appear to be issues with verifying
# a compressed file. Odd...
# 
echo "Creating new archive..." >> $LOG
tar --create --gzip --verbose --absolute-names --file=$archive --files-from=$FILELIST >> $LOG 2>&1
TAR_RC=$?

# useful output for later log file anlysis
echo "-- staged backup content completed at `date`." >> $LOG

# Although useful for debug purposes, cleanup the list of files to archive
rm -f $FILELIST

# check for 'tar' errors.  A '2' appear to be returned if we attempt to 'tar' a
# "corrupt" file, example: broken symbolic link or a file that is locked possibly.
if [ $TAR_RC -ne 0 ]; then
    echo "tar command failure. Return code is $TAR_RC, continuing..." >> $LOG
    if [ $TAR_RC -ne 2 ]; then
        echo "unexpected tar error, preparing to exit..." >> $LOG
        rm -f $archive
        exit_cleanup 6
    else
        echo "tar encountered in-use, locked, or invalid file, continuing..." >> $LOG
    fi
fi


#
# Some cleanup...
#
umount /mnt/dos


#
# Now move this backup file to it proper location
#
if [ $BACKUP_TYPE -eq 0 ]; then

    # output to DVD
    copyDumpToDVD $DUMP_DIR $ARCHIVE $DVD_MOUNTPOINT
    copyRC=$?
    if [ $copyRC -ne 0 ]; then
        exit_cleanup $copyRC
    fi
   
elif [ $BACKUP_TYPE -eq 1 ]; then

    # to remote (NFS/Samba) mount. Grab remaining program args from input
    SERVER=$3
    RESOURCE=$4
    FSTYPE=$5
    OPTIONS=$6
    copyDumpToMount $DUMP_DIR $ARCHIVE $SERVER $RESOURCE $FSTYPE "$OPTIONS"
    copyRC=$?
    
    # whether the backup worked or not, we should kill the portmap service if
    # we started it.
    echo "attempt to stop the portmap service..." >> $LOG
    if test -n "$PID" ; then
        echo "portmap was running prior to script execution - not terminating the service." >> $LOG
    else
        echo "now terminating the portmap service..." >> $LOG
        kill -9 $NEW_PID
    fi
    
    if [ $copyRC -ne 0 ]; then
        exit_cleanup $copyRC
    fi
   
elif [ $BACKUP_TYPE -eq 2 ]; then

    # to ftp server. Grab remaining program args from input
    SERVER=$3
    USERID=$4
    PASSWORD=$5
    ftpDumpToServer $DUMP_DIR $ARCHIVE $SERVER $USERID $PASSWORD
    copyRC=$?
    if [ $copyRC -ne 0 ]; then
        exit_cleanup $copyRC
    fi
    
fi


#
# That's all folks!
#
exit_cleanup 0
